const nameEle = document.querySelector('.username');
const passwordEle = document.querySelector('.password');
const btnEle = document.querySelector('.btn');

// * 检测初始状态
let nameFlag = false;
let passwordFlag = false;

nameEle.onblur = ()=>{
    const val = nameEle.value;
    if(val){
        const reg = /^[a-zA-Z0-9_-]{4,16}$/
        // * 正则检测通过
        if(reg.test(val)){
            // ? 在检测通过，再发同名检测
            $.ajax({
                type:'get',
                url:'http://localhost:3000/checkNameDup',
                data:{
                    name : val
                },
                success : (data)=>{
                   
                    // * true 重名 / false 不重名
                    if(data){
                        nameFlag = false;
                        alert('用户名重名');
                    }else{
                        nameFlag = true;
                    }
                    controlBtnDisabled();
                }
            })

            console.log('end')
        }else{
            nameFlag = false;
            controlBtnDisabled();
            alert('用户名不符合要求')
        } 
    }else{
        nameFlag = false;
        controlBtnDisabled();
    }
}

passwordEle.onblur = ()=>{
    const val = passwordEle.value;

    if(val){
        const reg = /^[a-zA-Z0-9_-]{8,15}$/
        if(reg.test(val)){
            passwordFlag = true;
        }else{
            passwordFlag = false;
            alert('密码不符合要求');
        }
    }else{
        passwordFlag = false;
    }
    controlBtnDisabled();
}

// * 提交
btnEle.onclick = ()=>{
    $.ajax({
        type:'post',
        url:'http://localhost:3000/regist',
        data:{
            name : nameEle.value,
            password: passwordEle.value
        },
        success: (data)=>{
            alert('成功');
        }
    })
}

function controlBtnDisabled(){
    btnEle.disabled = !(nameFlag && passwordFlag)
}


